package com.bruip.ch01;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.List;
import java.util.function.Predicate;

/**
 * @author yuxi
 * @version 1.0
 * @date 2025/10/22
 * @Description:
 */
public class Test06_predicate {
    public static void main(String[] args) {
        int[] arr={10,20,30,40,50,60,70,80};
        Predicate<Integer> p1=x->x>40;
        Integer[] arr1=filter(arr,p1);
        System.out.println(Arrays.toString(arr1));
        Predicate<Integer> p2=x->x<100;
        Integer[] arr2=filter(arr,p2);
        System.out.println(Arrays.toString(arr2));
        Predicate<Integer> p3=p1.and(p2);//x->(x>40)&&(x<100)
        Integer[] arr3=filter(arr,p3);
        System.out.println(Arrays.toString(arr3));
        Predicate<Integer> p4=p1.or(p2);//x->(x>40)||(x<100)
        Integer[] arr4=filter(arr,p4);
        System.out.println(Arrays.toString(arr4));
        Predicate<Integer> p5=p1.negate();//x->!(x>40)
        Integer[] arr5=filter(arr,p5);
        System.out.println(Arrays.toString(arr5));
    }
    //封装到方法中：行为参数化
    public static Integer[] filter(int[] arr, Predicate<Integer> predicate){
        List<Integer> list=new ArrayList<>();
        for(int i:arr){
            if(predicate.test(i)){
                list.add(i);
            }
        }
        Integer[] result=new Integer[list.size()];
        return list.toArray(result);

    }
}
